<?php
namespace app\controllers\h5\my;

use app\commission\ReceivedCommission;
use app\controllers\h5\base\H5Controller;

use app\models\order\Order as Model;
use app\models\order\OrderLogistics;
use app\models\system\SetExpressCompany;
use app\models\user\UserAccount;
use app\models\UserBalance;
use app\models\ZRegion;
use app\util\BirdExpress;

/**
 * my order
 *
 * Class Order
 * @package app\controllers\h5\my
 */
class OrderController extends H5Controller
{
    public function actionList()
    {
        $s = intval($this->post('status'));

        // status: h5 to model
        switch ($s) {
            case 1:
                $status = Model::$statusMapping['FINISH'];
                break;
            case 2:
                $status = Model::$statusMapping['NON_PAYMENT'];
                break;
            case 3:
                $status = Model::$statusMapping['PAID'];
                break;
            case 4:
                $status = Model::$statusMapping['WAIT_RECEIVING'];
                break;
            case 5:
                $status = Model::$statusMapping['RECEIVED'];
                break;
            case 6:
                $status = Model::$statusMapping['SERVICE'];
                break;
            case 7:
                $status = Model::$statusMapping['CANCEL'];
                break;
            default:
                $status = Model::$statusMapping['ALL'];
        }

        $page = intval($this->post('page', $this->page));
        $pageSize = intval($this->post('pageSize', $this->pageSize));

        $query = Model::find()
            ->andWhere(['user_id' => $this->user->id])
            ->andWhere(['!=', 'status', Model::$statusMapping['DELETE']]);


        if ($status > Model::$statusMapping['ALL']) {
            $query->andWhere(['status' => $status]);
        }

        // 待发货[收货], 取消云仓订单
        if ($status == Model::$statusMapping['PAID'] || $status == Model::$statusMapping['WAIT_RECEIVING']) {
            $query->andWhere(['is_store' => 0]);
        }

        $totalCount = $query->count();
        $totalPage = ceil($totalCount / $pageSize);

        $list = $query->orderBy(['id' => SORT_DESC])
            ->offset(($page - 1) * $pageSize)
            ->limit($pageSize)
            ->with([
                'item', 'item.product', 'item.product.mainImage', 'item.logistics', 'item.logistics.company',
                'address', 'address.city'
            ])
            ->asArray()
            ->all();

        foreach ($list as &$item) {
            if ($item['address']) {
                $item['address']['nickname'] = base64_decode($item['address']['nickname']);

                // var_dump($item);exit;

                // update city
                $item['address']['city'] = [
                    'province' => ZRegion::find()->where(['code' => $item['address']['province_id']])->select(['name'])->scalar(),
                    'city' => ZRegion::find()->where(['code' => $item['address']['city_id']])->select(['name'])->scalar(),
                    'area' => ZRegion::find()->where(['code' => $item['address']['area_id']])->select(['name'])->scalar(),
                ];
            }
        }

        return $this->successEncode([
            $this->list => $list,
            $this->totalCount => (int)$totalCount,
            $this->totalPage => $totalPage,
            $this->currentPage => $page
        ]);
    }

    /**
     * reset pay order
     *
     * @return array|string[]|\yii\web\Response
     */
    public function actionResetPay()
    {
        $order_id = intval($this->post('order_id'));

        $order = Model::findOne(['id' => $order_id]);

        if (!$order || $order->user_id != $this->user->id || $order->status != Model::$statusMapping['NON_PAYMENT']) {
            return $this->fail('错误操作');
        }

        $order->sn = Model::generateSn();
        if ($order->save()) {
            return $this->success();
        }

        return $this->fail();
    }

    public function actionFinish()
    {
        $order_id = intval($this->post('order_id'));

        $order = Model::findOne(['id' => $order_id]);

        if (!$order || $order->user_id != $this->user->id || $order->status != Model::$statusMapping['SERVICE']) {
            return $this->fail('错误操作');
        }

        $order->status = Model::$statusMapping['FINISH'];
        if ($order->save()) {
            return $this->success();
        }

        return $this->fail();
    }

    public function actionDelete()
    {
        $order_id = intval($this->post('order_id'));

        $order = Model::findOne(['id' => $order_id]);

        if (!$order || $order->user_id != $this->user->id) {
            if ($order->status != Model::$statusMapping['CANCEL'] || $order->status != Model::$statusMapping['NON_PAYMENT']) {
                return $this->fail('错误操作');
            }
        }

        $order->status = Model::$statusMapping['DELETE'];
        if ($order->save()) {

            // 退回余额
            $account = UserAccount::findOne(['user_id' => $order->user_id]);
            if ($account && $account->lock_balance >= $order->use_balance) {

                UserBalance::addLog($this->user->id,
                    $account->balance, +$order->use_balance, $account->balance + $order->use_balance, '取消订单', $order->id);

                $account->lock_balance -= $order->use_balance;
                $account->balance += $order->use_balance;
                $account->save();
            }

            return $this->success();
        }

        return $this->fail();
    }

    public function actionUrge()
    {
        $order_id = intval($this->post('order_id'));

        $order = Model::findOne(['id' => $order_id]);

        if (!$order || $order->user_id != $this->user->id || $order->status != Model::$statusMapping['PAID']) {
            return $this->fail('错误操作');
        }

        return $this->success();
    }

    public function actionConfirmReceived()
    {
        $order_id = intval($this->post('order_id'));

        $order = Model::findOne(['id' => $order_id]);

        if (!$order || $order->user_id != $this->user->id || $order->status != Model::$statusMapping['WAIT_RECEIVING']) {
            return $this->fail('错误操作');
        }

        $order->status = Model::$statusMapping['RECEIVED'];
        if ($order->save()) {

            // commission
            ReceivedCommission::done($order->id);

            return $this->success();
        }

        return $this->fail();
    }

    public function actionExpress()
    {
        $logistics_id = $this->post('logistics_id');

        $model = OrderLogistics::findOne(['id' => $logistics_id]);

        if ($model) {
            $code = SetExpressCompany::find()
                ->where(['id' => $model->express_company_id])
                ->select(['code'])
                ->scalar();

            // var_dump($code, $model->express_sn);exit;

            $express = BirdExpress::getOrderTracesByJson($code, $model->express_sn);

            // var_dump($express);exit;

            if ($express) {
                return $this->successEncode([
                    'express' => $express
                ]);
            }
        }

        return $this->fail();

    }

    // todo 这个可以当核销用
    public function actionScanQrcode()
    {
        $item_id = $this->post('item_id');

        // var_dump($item_id);exit;

        return $this->fail('核销功能已关闭');
    }
}